package com.example.service;

import com.example.dao.BootDao;
import com.example.dao.CarDao;
import com.example.entity.CarEntity;
import com.example.interceptor.CarsPage;
import com.example.interceptor.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.*;

@Service
public class CarServiceImpl implements  CarService {
    @Autowired
    private CarDao dao;
    @Autowired
    private BootDao bootDao;
    @Override
    public void insertCar(CarEntity carEntity) {
        dao.insertCar(carEntity);
    }

    @Override
    public CarEntity getCar(long id) {

        return dao.getCar(id);
    }

    @Override
    public void deleteCar(long id) {
        //此处可以判断是否抛出异常，也可以由controller检查

        dao.deleteCar(id);
    }

    @Override
    public int getCarAndBootNum() {
        int total=0;
        ExecutorService exxcutor = Executors.newFixedThreadPool(2);//可以设置成静态成员变量，
        // 如果是service已经是spring管理，可以设置成成员变量
        CompletionService<Integer> pool = new ExecutorCompletionService<Integer>(exxcutor);
        pool.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {

                return dao.getTotal();
            }
        });
        pool.submit(()->{
            return bootDao.getTotal();
        });
        exxcutor.shutdown();//不关闭浪费资源，一直有两个线程以及线程池资源浪费
        try {
            total += pool.take().get();
            total += pool.take().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return total;
    }

    /*
    通过拦截statementhandler的prepare方法，改变预编译语句
     */
    @Override
    public List<CarEntity> getCars() {
        //Pageable pageable = new PageRequest(0,1);
        Page page = new Page(1,3);
        List<CarEntity> entities =dao.getCarS(page);
        System.out.println(page);
        return entities;
    }

    /*
    通过拦截statementhandler的prepare方法，改变预编译语句
     */
    @Override
    public CarsPage getCarsByName(BigDecimal price, Page page) {
        //这是通过拦截statementhandler实现的代码
//        List<CarEntity> entities =dao.getCarSByName(page,price);
//        CarsPage carsPage = new CarsPage(page);
//        System.out.println(page);
//        carsPage.setCarEntities(entities);
//        return carsPage;
        //通过拦截executor实现的代码
        return dao.getCarSByName(page,price);
    }
}
